package controller;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/* Singleton */
public class Localizer {
    
    private static final String fileName = "lang.xml";
    
    private static Localizer _localizer;
    
    private Document doc;
    
    protected Localizer() {
        initDocument();
    }
    private void initDocument() {
        
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(new File(fileName));
            doc.getDocumentElement().normalize();
            
        } catch (SAXException ex) {
            Logger.getLogger(Localizer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Localizer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Localizer.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    public boolean canLocalize() {
        return doc != null;
    }
    public String getText(Localizations localization) {
        NodeList list = doc.getElementsByTagName(localization.getName());
        if(list.getLength() > 0) {
            Node n = list.item(0);
            return n.getTextContent();
        }
        return "";
    }
    
    
    public static Localizer getInstance() {
        if(_localizer == null) {
            _localizer = new Localizer();
        }
        return _localizer;
    }
}